package com.atguigu.tingshu.search.runners;

import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import org.jetbrains.annotations.NotNull;
import org.redisson.api.RBloomFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.List;

@SuppressWarnings({"unchecked", "rawtypes"})
//@Component 有效 项目中不使用
public class BloomFilterRunners implements ApplicationRunner, ApplicationContextAware {

    private ApplicationContext applicationContext;
    Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * @description: run方法在spring容器启动完毕的时候得到
     * @author: baosi
     * @date: 2025/3/25 22:24
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        //从spring容器中拿到布隆过滤器的bean
        RBloomFilter rBloomFilter = applicationContext.getBean("rBloomFilter", RBloomFilter.class);
        //从spring容器中获取应用的Bean
        ItemServiceImpl itemServiceImpl = applicationContext.getBean("itemServiceImpl", ItemServiceImpl.class);
        //获取数据
        List<Long> albumInfoIdList = itemServiceImpl.getAlbumInfoIdList();
        //将数据放到布隆过滤器中
        for (Long albumId : albumInfoIdList) {
            rBloomFilter.add(albumId);
        }
        //布隆过滤器元素是否同步进去
        logger.info("分布式布隆过滤器的元素个数：" + rBloomFilter.count());
    }

    @Override
    public void setApplicationContext(@NotNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
